<?php

namespace App\Admin\Eloquent;

use App\Exceptions\BusinessException;

class Navigation extends Model
{
    protected $fillable = ['name','link','description','sort','parent_id'];

    /**
     * 根据排除该id 查询父级导航
     *
     * @param int $id
     * @return array
     */
    public static function getParents(int $id = -1 )
    {
        return Navigation::where('id', '!=', $id)
            ->where('parent_id', '!=', $id)
            ->lists('name', 'id');
    }

    /**
     * 根据导航名称和id模糊查询导航导航
     *
     * @param array $query
     * @param int $pagesize
     * @return mixed
     */
    public static function paging_query(array $query=[],int $pagesize){

        $navigations=Navigation::leftJoin('navigations as a', 'a.id', '=', 'navigations.parent_id')
            ->select('navigations.id', 'navigations.name', 'a.name as parent_name', 'navigations.sort')
            ->orderBy('navigations.created_at', 'desc');

        //追加分页条件
        if (isset($query['parent_id'])&&!empty($query['parent_id']))
            $navigations->where('navigations.parent_id', $query['parent_id']);

        if (isset($query['name'])&&!empty($query['name']))
            $navigations->where('navigations.name', 'like', '%' . $query['name'] . '%');


        $navigations = $navigations->paginate($pagesize);

        //追加分页条件
        if (isset($query['parent_id'])&&!empty($query['parent_id']))
            $navigations->appends(['parent_id' => $query['parent_id']]);

        if (isset($query['name'])&&!empty($query['name']))
            $navigations->appends(['name' => $query['name']]);

        return $navigations;
    }
    public function delete(){

        if($this::where('parent_id',$this->id)->exists()){
            throw new BusinessException("不能删除父级导航,请先删除子级导航 error-id:".$this->id);
        }

        return parent::delete();
    }
}